import Vue from 'vue'
import Vuex from 'vuex'
import router from '@/router'
import { login, userInfo } from '@/api/login'

const UPDATE_LOGIN = 'UPDATE_LOGIN'
const UPDATE_USER_INFO = 'UPDATE_USER_INFO'
const UPDATE_LOGOUT = 'UPDATE_LOGOUT'
const UPDATE_TOKEN = 'UPDATE_TOKEN'

Vue.use(Vuex)

export const state = {
    EventBus: new Vue(),
    token: sessionStorage.getItem('token') || '',
    isLogin: sessionStorage.getItem('token') ? true : false,
    userInfo: sessionStorage.getItem('userInfo') ? JSON.parse(sessionStorage.getItem('userInfo')) : { mobile: 18838947828 },
    loginPopup: false,
}

const vuex = new Vuex.Store({
    state,
    mutations: {
        [UPDATE_LOGIN](state, payload) {
            const { status } = payload
            state.isLogin = status
        },
        [UPDATE_LOGOUT](state) {
            state.token = ''
            state.isLogin = false
            state.userInfo = {}
            sessionStorage.setItem('token', '')
            sessionStorage.setItem('userInfo', '')
        },
        [UPDATE_TOKEN](state, payload) {
            state.token = payload.token
            sessionStorage.setItem('token', payload.token)
        },
        [UPDATE_USER_INFO](state, payload) {
            state.userInfo = payload
            sessionStorage.setItem('userInfo', JSON.stringify(payload))
        },
    },
    actions: {
        setLoginInfo({ commit, dispatch }, res) {
            const next = async () => {
                commit(UPDATE_LOGIN, {
                    status: true,
                    token: res.data.token,
                })

                commit(UPDATE_TOKEN, {
                    token: res.data.token,
                })

                commit(UPDATE_USER_INFO, res.data.login_info.user_info)

                try {
                    await dispatch('gtUserMemberInfo')
                } catch (e) {
                    console.log('gtUserMemberInfo err')
                }
                dispatch('getUserMemberGradeDetail')

                state.EventBus.$emit('login-success')
            }

            if (res.data && res.data.result && res.data.result.redirect_url) {
                return dispatch('doJavaLogin', res.data.result.redirect_url).then(() => {
                    return next()
                })
            } else {
                return next()
            }
        },
        signInAction({ commit, dispatch }, params) {
            return new Promise((resolve, reject) => {
                const { mobile, pwd, remember } = params
                login({
                    mobile,
                    pwd,
                    remember,
                })
                    .then((res) => {
                        const { mobile, pwd, remember, _pwd } = params

                        if (res.code == 0) {
                            const next = async () => {
                                commit(UPDATE_LOGIN, {
                                    status: true,
                                    token: res.data.token,
                                })

                                commit(UPDATE_TOKEN, {
                                    token: res.data.token,
                                })

                                commit(UPDATE_USER_INFO, res.data.login_info.user_info)

                                if (state.redirectPath) {
                                    let { path, query, params } = state.redirectPath
                                    router.push({
                                        path,
                                        query,
                                        params,
                                    })
                                }

                                if (remember === 1) {
                                    commit(UPDATE_REMEMBER_INFO, {
                                        mobile,
                                        pwd: _pwd,
                                    })
                                } else {
                                    commit(UPDATE_REMEMBER_INFO, false)
                                }

                                try {
                                    await dispatch('gtUserMemberInfo')
                                } catch (e) {
                                    console.log('gtUserMemberInfo err')
                                }

                                state.EventBus.$emit('login-success')

                                resolve(res)

                                commit(UPDATE_LOGIN_POPUP)
                            }

                            if (res.data && res.data.result && res.data.result.redirect_url) {
                                dispatch('doJavaLogin', res.data.result.redirect_url).then(() => {
                                    next()
                                })
                            } else {
                                next()
                            }
                        }
                    })
                    .catch(reject)
            })
        },
        getUserData({ commit }) {
            return userInfo()
                .then((res) => {
                    commit(UPDATE_USER_DATA, res)
                })
                .catch()
        },
    },
})

export default vuex
